package http

import (
	"dbagent/internal/conf"
	"dbagent/internal/service"
	"dbagent/pkg/util"
	"net/http"
	"strconv"

	"github.com/go-kratos/kratos/pkg/ecode"
	"github.com/go-kratos/kratos/pkg/log"
	bm "github.com/go-kratos/kratos/pkg/net/http/blademaster"
)

func StartNc(ctx *bm.Context) {
	mysqlBackupService := new(service.MysqlBackup)
	err := ctx.Bind(mysqlBackupService)

	if err != nil {
		ctx.JSON(nil, ecode.Errorf(http.StatusUnprocessableEntity, "bind MysqlBackup req error: %v", err))
		return
	}

	mysqlBackupService.Conn = conf.BackupDb
	clusterBackupDir, taskPoint, err := mysqlBackupService.StartNc()

	if err != nil {
		ctx.JSON(nil, ecode.Errorf(http.StatusBadRequest, err.Error()))
		return
	}
	result := make(map[string]interface{})

	result = map[string]interface{}{
		"backup_dir": clusterBackupDir,
		"task_point": taskPoint,
	}

	ctx.JSON(result, nil)

	return
}

func StartFullBackup(ctx *bm.Context) {
	mysqlBackupService := new(service.MysqlBackup)
	err := ctx.Bind(mysqlBackupService)

	if err != nil {
		ctx.JSON(nil, ecode.Errorf(http.StatusUnprocessableEntity, "bind MysqlBackup req error: %v", err))
		return
	}

	mysqlBackupService.Conn = conf.BackupDb
	go func() {
		var message string
		status, err := mysqlBackupService.StartFullBackup()
		if err != nil {
			message = err.Error()
		}

		if len(mysqlBackupService.Callback) == 0 {
			log.Error("StartFullBackup function callback params is empty")
			return
		}

		params := "backup_id=" + strconv.Itoa(mysqlBackupService.BackupId) + "&status=" + strconv.Itoa(status) + "&log=" + message + "&method=fullBack"
		log.Info(mysqlBackupService.Callback)
		log.Info(params)
		_, err = util.HttpPost(mysqlBackupService.Callback, params)
		if err != nil {
			log.Error(err.Error())
		}
	}()

	data := make(map[string]interface{})
	ctx.JSON(data, nil)

	return
}

func StartRedoLog(ctx *bm.Context) {
	mysqlBackupService := new(service.MysqlBackup)
	err := ctx.Bind(mysqlBackupService)

	if err != nil {
		ctx.JSON(nil, ecode.Errorf(http.StatusUnprocessableEntity, "bind MysqlBackup req error: %v", err))
		return
	}

	mysqlBackupService.Conn = conf.BackupDb
	go func() {
		var message string
		status, err := mysqlBackupService.StartRedoLog()
		if err != nil {
			message = err.Error()
		}

		if len(mysqlBackupService.Callback) == 0 {
			log.Error("StartRedoLog function callback params is empty")
			return
		}
		params := "backup_id=" + strconv.Itoa(mysqlBackupService.BackupId) + "&status=" + strconv.Itoa(status) + "&log=" + message + "&method=redo"
		_, err = util.HttpPost(mysqlBackupService.Callback, params)
		if err != nil {
			log.Error(err.Error())
		}

	}()

	data := make(map[string]interface{})
	ctx.JSON(data, nil)

	return
}
